<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px"
      class="search-form">
      <el-form-item label="用户账号" prop="userName">
        <el-input v-model="queryParams.userName" placeholder="请输入用户账号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="手机号码" prop="phonenumber">
        <el-input v-model="queryParams.phonenumber" placeholder="请输入手机号码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="授权企业名称" prop="corpName">
        <el-input v-model="queryParams.corpName" placeholder="请输入授权企业名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item class="search-buttons">
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="userList" border highlight-current-row style="width: 100%">
      <el-table-column label="企业名称" align="center" prop="corpName" min-width="120" />
      <el-table-column label="用户账号" align="center" prop="userName" min-width="100" />
      <el-table-column label="手机号码" align="center" prop="phonenumber" min-width="120" />
      <el-table-column label="已绑定医院" align="center" prop="hospitalName" min-width="150" />
      <el-table-column label="已绑定医生" align="center" prop="doctorName" min-width="150" />

      <el-table-column label="操作" align="center" width="120" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-connection" @click="handleBind(scope.row)"
            v-hasPermi="['digitaldoctorops:user:edit']">
            绑定
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" class="pagination" />

    <!-- 绑定医生对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body :close-on-click-modal="false">
      <el-form ref="bindForm" :model="bindForm" :rules="rules" label-width="120px" class="dialog-form">
        <el-form-item label="当前用户" prop="userName">
          <el-input v-model="bindForm.userName" disabled />
        </el-form-item>

        <el-form-item label="医院名称" prop="ghHospitalCode">
          <el-select v-model="bindForm.ghHospitalCode" placeholder="请选择医院名称" filterable clearable
            @change="handleHospitalChange" style="width: 100%">
            <el-option v-for="item in hoslist" :key="item.hospitalCode" :label="item.hospitalName"
              :value="item.hospitalCode" />
          </el-select>
        </el-form-item>

        <el-form-item label="医生名称" prop="ghDoctorCode">
          <el-select v-model="bindForm.ghDoctorCode" placeholder="请选择医生名称" filterable clearable
            @change="handleDoctorChange" style="width: 100%" :disabled="!bindForm.ghHospitalCode">
            <el-option v-for="item in doclist" :key="item.doctorCode" :label="item.doctorName"
              :value="item.doctorCode" />
          </el-select>
        </el-form-item>

        <el-form-item label="医生码" prop="docma">
          <el-input v-model="bindForm.docma" placeholder="医生码" disabled />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitBindForm" :loading="submitLoading">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listUser, getisyiyuan, gethoslist, getdoclist, bangdoc } from "@/api/digitaldoctorops/user";

export default {
  name: "UserBinding",
  data() {
    return {
      // 加载状态
      loading: true,
      submitLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: null,
        phonenumber: null,
        corpName: null,
      },
      // 绑定表单参数
      bindForm: {
        userId: null,
        userName: null,
        ghHospitalCode: null,
        ghDoctorCode: null,
        docma: null
      },
      // 表单校验
      rules: {
        ghHospitalCode: [
          { required: true, message: "请选择医院名称", trigger: "change" }
        ],
        ghDoctorCode: [
          { required: true, message: "请选择医生名称", trigger: "change" }
        ],
      },
      // 医院列表
      hoslist: [],
      // 医生列表
      doclist: []
    };
  },
  created() {
    this.getList();
    this.loadHospitalList();
  },
  methods: {
    // 加载医院列表
    loadHospitalList() {
      gethoslist().then(res => {
        this.hoslist = res.data || [];
      }).catch(() => {
        this.hoslist = [];
      });
    },

    // 医院选择变化
    handleHospitalChange(hospitalCode) {
      this.bindForm.ghDoctorCode = null;
      this.bindForm.docma = null;

      if (hospitalCode) {
        this.loading = true;
        getdoclist({ hospitalCode }).then(res => {
          this.doclist = res.data || [];
        }).finally(() => {
          this.loading = false;
        });
      } else {
        this.doclist = [];
      }
    },

    // 医生选择变化
    handleDoctorChange(doctorCode) {
      if (doctorCode) {
        const selectedDoctor = this.doclist.find(item => item.doctorCode === doctorCode);
        this.bindForm.docma = selectedDoctor ? selectedDoctor.doctorCode : '';
      } else {
        this.bindForm.docma = '';
      }
    },

    // 查询用户列表
    getList() {
      this.loading = true;
      listUser(this.queryParams).then(response => {
        this.userList = response.rows;
        this.total = response.total;
      }).finally(() => {
        this.loading = false;
      });
    },

    // 取消操作
    cancel() {
      this.open = false;
      this.resetBindForm();
    },

    // 重置绑定表单
    resetBindForm() {
      this.bindForm = {
        userId: null,
        userName: null,
        ghHospitalCode: null,
        ghDoctorCode: null,
        docma: null
      };
      this.$refs.bindForm && this.$refs.bindForm.resetFields();
    },

    // 搜索操作
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    // 重置搜索
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    // 绑定医生操作
    handleBind(row) {
      this.resetBindForm();
      this.bindForm.userId = row.userId;
      this.bindForm.userName = row.userName;

      // 加载已绑定的医院和医生信息
      getisyiyuan({ id: row.userId }).then(response => {
        if (response.data) {
          this.bindForm.hospitalName = response.data;
        }
        this.open = true;
        this.title = "绑定医生";

        // 如果已有医院信息，加载对应医生列表
        if (row.ghHospitalCode) {
          this.bindForm.ghHospitalCode = row.ghHospitalCode;
          this.handleHospitalChange(row.ghHospitalCode);
          this.bindForm.ghDoctorCode = row.ghDoctorCode;
          this.bindForm.docma = row.ghDoctorCode;
        }
      });
    },

    // 提交绑定表单
    submitBindForm() {
      this.$refs["bindForm"].validate(valid => {
        if (valid) {
          this.submitLoading = true;

          bangdoc({
            userId: this.bindForm.userId,
            ghDoctorCode: this.bindForm.docma,
            ghHospitalCode: this.bindForm.ghHospitalCode
          }).then(response => {
            this.$modal.msgSuccess("绑定成功");
            this.open = false;
            this.getList();
          }).finally(() => {
            this.submitLoading = false;
          });
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;

  .search-form {
    margin-bottom: 20px;

    .el-form-item {
      margin-bottom: 15px;
    }

    .search-buttons {
      float: right;
    }
  }

  .pagination {
    margin-top: 15px;
    text-align: right;
  }

  .dialog-form {
    padding: 10px 20px 0 0;
  }
}
</style>